﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.HtmlControls;
using System.Web.UI;

namespace GoodStuff.Web.Controls.Validation
{
    public static class ValidationFramework
    {
        public static void SetupValidators(this HtmlForm form, ValidationMessagePattern pattern,  params ValidationRule[] rules)
        {
            //find all the AutoValidators on this form and apply the rules.
            //
            foreach (AutoValidator autoValidator in FindControlsRecursive<AutoValidator>(form))
            {
                autoValidator.Pattern = pattern;
                autoValidator.Rules = rules.Where(r => r.Properties.Contains(autoValidator.Key));                
            }
        }


        /// <summary>
        /// returns all controls of a particular base class
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="startingControl"></param>
        /// <returns></returns>
        private static IEnumerable<T> FindControlsRecursive<T>(Control startingControl) where T : Control
        {
            foreach (Control activeControl in startingControl.Controls)
            {
                if (activeControl is T)
                {
                    yield return (T)activeControl;
                }
                else
                {
                    foreach (T t in FindControlsRecursive<T>(activeControl))
                    {
                        yield return t;
                    }
                }
            }
        }
    }

    public enum ValidationMessagePattern
    {
        AsText,
        AsSummary
    }
}
